package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author Lz
 * @date 2020-03-06 20:52
 * @week 星期五
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    private Pattern pathPattern = Pattern.compile("^[0-9]+$");

    //分页查询菜单数据
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (currentPage == null || currentPage <= 0) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }

        PageHelper.startPage(currentPage, pageSize);
        Page<Menu> page = menuDao.findPage(queryString);
        long total = page.getTotal();
        List<Menu> rows = page;
        return new PageResult(total, rows);
    }

    @Override
    public List<Map<String, Object>> findAllParentMenu() {
        List<Map<String, Object>> allParentMenu = menuDao.findAllParentMenu();
        return allParentMenu;
    }

    //添加菜单
    @Override
    public Result add(Menu menu) {
        String name = menu.getName();
        if (name == null || name.length() <= 0) {
            return new Result(false, "菜单名称不能为空");
        }
        Integer level = menu.getLevel();
        if (level != 1 && level != 2) {
            return new Result(false, "菜单级别只能为1或2");
        }
        String linkUrl = menu.getLinkUrl();
        if (level == 1 && linkUrl != null && linkUrl.length() > 0) {
            return new Result(false, "菜单级别为1时，访问路径必须为空");
        }
        if (level == 2 && linkUrl == null) {
            return new Result(false, "菜单级别为2时，必须设置访问路径");
        }
        if (linkUrl != null && !linkUrl.endsWith(".html")) {
            return new Result(false, "访问路径设置错误");
        }
        String path = menu.getPath();
        if (!pathPattern.matcher(path).matches()) {
            return new Result(false, "路径级别只能为一个正整数");
        }
        Integer priority = menu.getPriority();
        if (priority == null || priority <= 0) {
            return new Result(false, "菜单优先级必须为大于0的整数");
        }
        Menu menu1 = menuDao.priorityIsExist(menu);
        if (menu1 != null) {
            return new Result(false, "该优先级已经存在");
        }
        Integer parentMenuId = menu.getParentMenuId();
        if (level == 1 && parentMenuId != null) {
            return new Result(false, "当菜单级别为1时，不能设置关联菜单id");
        }
        if (level == 2 && (parentMenuId == null || parentMenuId <= 0)) {
            return new Result(false, "当菜单级别为2时，必须设置关联菜单");
        }
        String icon = menu.getIcon();
        if (level == 1 && (icon == null || icon.length() <= 0)) {
            return new Result(false, "当菜单级别为1时，必须设置菜单图标");
        }

        if (level == 2) {
            String parentPath = menuDao.getPathByParentMenuId(parentMenuId);
            menu.setPath("/" + parentPath + "-" + path);
        }

        String flag = menuDao.pathIsExist(menu.getPath());
        if (flag != null && flag.length() > 0) {
            return new Result(false, menu.getPath() + "路径已存在");
        }


        menuDao.add(menu);
        return new Result(true, "添加菜单成功");
    }

    @Override
    public Menu findById(Integer id) {
        Menu menu = menuDao.findById(id);
        Integer level = menu.getLevel();
        if (level == 2) {
            String path = menu.getPath();
            int index = path.indexOf("-");
            String substring = path.substring(1, index);
            menu.setPath(substring);
        }
        return menu;
    }

    @Override
    public Result edit(Menu menu) {
        Menu menu1 = menuDao.findById(menu.getId());

        String name = menu.getName();
        if (name == null || name.length() <= 0) {
            return new Result(false, "菜单名称不能为空");
        }
        Integer level = menu.getLevel();
        if (level != 1 && level != 2) {
            return new Result(false, "菜单级别只能为1或2");
        }
        String linkUrl = menu.getLinkUrl();
        if (level == 1 && linkUrl != null && linkUrl.length() > 0) {
            return new Result(false, "菜单级别为1时，访问路径必须为空");
        }
        if (level == 2 && linkUrl == null) {
            return new Result(false, "菜单级别为2时，必须设置访问路径");
        }
        if (linkUrl != null && !linkUrl.endsWith(".html")) {
            return new Result(false, "访问路径设置错误");
        }
        String path = menu.getPath();
        if (!pathPattern.matcher(path).matches()) {
            return new Result(false, "路径级别只能为一个正整数");
        }
        Integer priority = menu.getPriority();
        if (priority == null || priority <= 0) {
            return new Result(false, "菜单优先级必须为大于0的整数");
        }
        if (!menu1.getPriority().equals(priority)) {
            Menu menu2 = menuDao.priorityIsExist(menu);
            if (menu2 != null) {
                return new Result(false, "该优先级已经存在");
            }
        }
        Integer parentMenuId = menu.getParentMenuId();
        if (level == 1 && parentMenuId != null) {
            return new Result(false, "当菜单级别为1时，不能设置关联菜单id");
        }
        if (level == 2 && (parentMenuId == null || parentMenuId <= 0)) {
            return new Result(false, "当菜单级别为2时，必须设置关联菜单");
        }
        String icon = menu.getIcon();
        if (level == 1 && (icon == null || icon.length() <= 0)) {
            return new Result(false, "当菜单级别为1时，必须设置菜单图标");
        }

        if (level == 2) {
            String parentPath = menuDao.getPathByParentMenuId(parentMenuId);
            menu.setPath("/" + parentPath + "-" + path);
        }
        if (!menu1.getPath().equals(path)) {
            String flag = menuDao.pathIsExist(menu.getPath());
            if (flag != null && flag.length() > 0) {
                return new Result(false, menu.getPath() + "路径已存在");
            }
        }

        //如果修改的是1级菜单，要保证它的子菜单的前缀也修改
        if (level == 1) {
            //找到parentMenuId为该id的子菜单，对应修改其路径
            Integer id = menu.getId();
            List<Menu> childrenMenus = menuDao.findMenuByParentMenuId(id);
            for (Menu childrenMenu : childrenMenus) {
                String childrenMenuPath = childrenMenu.getPath();
                String finalPath = "/" + path + "-" + childrenMenuPath.split("-")[1];
                //修改子菜单的path
                childrenMenu.setPath(finalPath);
                menuDao.updateChildrenMenuPath(childrenMenu);
            }
        }
        menuDao.edit(menu);
        return new Result(true, "修改菜单成功");
    }

    @Override
    public Result delete(Integer id) {
        //检查该表与t_role的关联数据
        List<String> names = menuDao.findCountByMenuId(id);
        if (names != null && names.size() > 0) {
            String result = "(";
            for (int i = 0; i < names.size(); i++) {
                result += names.get(i);
                if (i < names.size() - 1) {
                    result += "、";
                }
                result += ")";
                return new Result(false, "该菜单与" + result + "角色进行关联，无法删除");
            }
        }

        //检查该表与自身的关联，即有没有子菜单
        List<Menu> children = menuDao.findChildren(id);
        if (children != null && children.size() > 0) {
            return new Result(false, "该菜单有子菜单，无法删除");
        }

        menuDao.deleteById(id);
        return new Result(true, "删除菜单成功");
    }

    @Override
    public List<Menu> getMenus(String username) {
        List<Menu> menus = menuDao.getMenus(username);
        for (Menu menu : menus) {
            Integer id = menu.getId();
            List<Menu> children = menuDao.findChildren(id);
            menu.setChildren(children);
        }
        return menus;
    }
}
